<?php

namespace backend\controllers;

use backend\jobs\OcrJob;
use yii;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\YueJuan;
use backend\models\Generalocr;
use PHPUnit\Framework\Exception;
use backend\models\GeneralocrSearch;
use backend\models\GeneralocrGroupSearch;
use yii\db\StaleObjectException;
use yii\helpers\ArrayHelper;

use Imagick;
use backend\models\GeneralocrPdf;
use yii\helpers\Url;

class YueJuanController extends \yii\web\Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public $layout = 'yue-juan';

    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 单个上传文件
     */
    public function actionUpload()
    {
        $model = new YueJuan();

        if (empty($_FILES['input-folder']['name'])) {
            echo json_encode(['error' => '请先选择要上传的文件']);
            return;
        }
//        echo json_encode(['error' => Yii::$app->request->post('file_id')]);

        $input_folder = $_FILES['input-folder'];
        $title = Yii::$app->request->post('title');
        $success = null;
        $filename = $input_folder['name'];
        $ext = explode('.', basename($filename));
        $path = "uploads" . DIRECTORY_SEPARATOR . date('Ymd');
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $extension = array_pop($ext);
        if (!in_array(strtolower($extension), ["jpg", "png", "jpeg", "pdf"])) {
            echo json_encode(['error' => '文件格式不正确']);
            return;
        }

        //上传pdf
        if (strtolower($extension) == 'pdf') {
            if (GeneralocrPdf::findOne(['filename' => $filename, 'user_id' => Yii::$app->user->id]) !== null) {
                echo json_encode(['error' => '已上传过了']);
                return;
            }
            $model->uploadPdf($input_folder, $title, Yii::$app->user->id);
            return;
        }

        //已有的图片不再保存不再识别
        if (($modelGeneralocr = Generalocr::find()->where(['filename' => $filename, 'title' => Yii::$app->request->post('title'), 'user_id' => Yii::$app->user->id,])->one()) !== null) {
            //不再识别图片
            echo json_encode(['error' => '此图片已经上传过了']);
            return;
        } else {
            //未上传过的图片上传
            $modelGeneralocr = new Generalocr();
            $target = $path . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . $extension;
            if (move_uploaded_file($input_folder['tmp_name'], $target)) {
                $values = [
                    'filename' => $filename,
                    'title' => Yii::$app->request->post('title'),
                    'user_id' => Yii::$app->user->id,
                    'path' => $target,
                    'order' => Yii::$app->request->post('file_id'),
                ];
                $modelGeneralocr->attributes = $values;
                if ($modelGeneralocr->save() == false) {
                    unlink($target);
                    echo json_encode(['error' => $filename . '图片保存失败' . serialize($modelGeneralocr->getFirstErrors())]);
                    return;
                } else {
                    //识别图片
//                    $model->imageOcr($modelGeneralocr->id);此部分放至队列中
                    $job_id = Yii::$app->queue->push(new OcrJob([
                        'url' => Yii::$app->request->hostInfo . Url::to(['yue-juan-queue/ocr']),
                        'id' => $modelGeneralocr->id,
                    ]));
                    $_SESSION['job'][] = ['job_id' => $job_id, 'filename' => $filename,];
                    echo json_encode(['info' => $filename . '图片已上传,处理中']);
                    return;
                }
            } else {
                echo json_encode(['error' => '无上传权限']);
                return;
            }
        }


    }

    public function actionReread($ids)
    {
        $ids = explode(',', $ids);
        if (is_array($ids) && count($ids) > 0) {
            foreach ($ids as $id) {
                $model = Generalocr::findOne($id);
                $job_id = Yii::$app->queue->push(new OcrJob([
                    'url' => Yii::$app->request->hostInfo . Url::to(['yue-juan-queue/ocr']),
                    'id' => $id,
                ]));
                $_SESSION['job'][] = ['job_id' => $job_id, 'filename' => $model->filename,];
            }
        }
    }

    public function actionReadNoQueue($id)
    {
        $model = new YueJuan();
        $model->imageOcr($id);
    }


    public function readImage($modelGeneralocr, $target)
    {
        //识别图片
        $ret = $this->getGeneralOcr($target);
        if (is_array($ret) && empty($ret['errorcode'])) {
            $itemString = '';
            foreach ($ret['items'] as $item) {
                $itemString .= $item['itemstring'];
            }
            $modelGeneralocr->ocr_string = $itemString;
            $modelGeneralocr->ocr_ret = json_encode($ret);
            if ($modelGeneralocr->save()) {
                echo json_encode(['success' => '保存成功']);
            } else {
                echo json_encode(['error' => '保存失败' . serialize($modelGeneralocr->getFirstErrors())]);
            }
            return;
        } else {
            echo json_encode(['error' => '图片已上传，但未能识别图片内容']);
            return;
        }
    }

    public function actionUploadBatch()
    {
        if (empty($_FILES['images'])) {
            echo json_encode(['error' => '请先选择要上传的文件']);
            // or you can throw an exception
            return; // terminate
        }

// get the files posted
        $images = $_FILES['images'];
        $title = Yii::$app->request->post('title');

        // a flag to see if everything is ok
        $success = null;

        // file paths to store
        $paths = [];
        $values = [];

        // get file names
        $filenames = $images['name'];

        $output = [];
        // loop and process files
        for ($i = 0; $i < count($filenames); $i++) {
            $filename = $filenames[$i];
            if (Generalocr::find()->where(['filename' => $filename, 'title' => Yii::$app->request->post('title'), 'user_id' => Yii::$app->user->id,])->one() !== null) {
                $values[$i] = [
                    'title' => $title,
                    'filename' => $filename,
                    'user_id' => Yii::$app->user->id,
                ];
                $success = true;
                continue;//已有图片不现上传
            }
            $ext = explode('.', basename($filename));
            $path = "uploads" . DIRECTORY_SEPARATOR . date('Ymd');
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
            $target = $path . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
            if (move_uploaded_file($images['tmp_name'][$i], $target)) {
                $success = true;
                $paths[] = $target;
                $values[$i] = [
                    'title' => $title,
                    'filename' => $filename,
                    'path' => $target,
                    'user_id' => Yii::$app->user->id,
                ];
            } else {
                $success = false;
                break;
            }
        }

// check and process based on successful status
        if ($success === true) {
            // call the function to save all data to database
            // code for the following function `save_data` is not
            // mentioned in this example
//            save_data($values);
            if (is_array($values) && count($values) > 0) {
                $model = new Generalocr();
                $success = 0;
                $failure = 0;
                $failed_info = [];
                $ocr_error = [];
                foreach ($values as $value) {
                    if (($modelClone = Generalocr::find()->where($value)->one()) == null) {//检查是否已经存过title,filename,user_id
                        $modelClone = clone $model;
                        $modelClone->attributes = $value;
                    }

                    //识别图片
                    if ($value['path']) {
                        $ret = $this->getGeneralOcr($value['path']);
                    } else {
                        $ret = $this->getGeneralOcr($modelClone->path);
                    }

                    if (is_array($ret) && empty($ret['errorcode'])) {
                        $itemString = '';
                        foreach ($ret['items'] as $item) {
                            $itemString .= $item['itemstring'];
                        }
                        $modelClone->ocr_string = $itemString;
                        $modelClone->ocr_ret = json_encode($ret);
                    } else {
                        $output['error'] .= $value['filename'] . "图片已上传，但未能识别图片内容<br>";
//                        echo json_encode($ocr_error);
                    }

                    if ($modelClone->save()) {
                        $success++;
                    } else {
                        $failure++;
                        $failed_info[] = $value['filename'] . $modelClone->getFirstErrors();
                    }
                }


            }

            // store a successful response (default at least an empty array). You
            // could return any additional response info you need to the plugin for
            // advanced implementations.
            if ($failure > 0) {
                $output = ['error' => $success . '成功，' . $failure . '失败。' . serialize($failed_info)];
            }


            // for example you can get the list of files uploaded this way
            // $output = ['uploaded' => $paths];
        } elseif ($success === false) {
            $output = ['error' => 'Error while uploading images. Contact the system administrator'];
            // delete any uploaded files
            foreach ($paths as $file) {
                unlink($file);
            }
        } else {
            $output = ['error' => 'No files were processed.'];
        }

// return a json encoded response for plugin to process successfully
        echo json_encode($output);
    }

    public function getGeneralOcr($path)
    {
        $model = new YueJuan();
        $ret = $model->generalocr($path);
        return $ret;

    }

    public function actionScan()
    {
//        $searchModel = new GeneralocrGroupSearch();
//        $searchModel->user_id = Yii::$app->user->id;
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
//            'searchModel' => $searchModel,
//            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionMyUpload()
    {
        $modelYueJuan = new YueJuan();
        $modelYueJuan->getJobResult();
        $searchModel = new GeneralocrGroupSearch();
        $searchModel->user_id = Yii::$app->user->id;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('my-upload', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionScanView()
    {
        $modelYueJuan = new YueJuan();
        $modelYueJuan->getJobResult();

        $searchModel = new GeneralocrSearch();
        $get = Yii::$app->request->get();
        $searchModel->user_id = $user_id = Yii::$app->user->id;

        $title = $get['title'] ? $get['title'] : $get['GeneralocrSearch']['title'];

        $searchModel->title = $title;
        $map = "`user_id`=$user_id";
        if ($title) {
            $map .= " AND `title`='" . $title . "'";
        }
        $ocr_string = $get['GeneralocrSearch']['ocr_string'];
        $arr_win = [];
        if ($ocr_string) {
            $map .= " AND `ocr_string` like '%" . $ocr_string . "%'";
            $query_id = Generalocr::find()->where($map)->select(['id'])->orderBy(['id' => SORT_ASC])->asArray()->all();
            $arr_win = ArrayHelper::getColumn($query_id, 'id');
        }

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $arr_win_result = [];
        if (is_array($arr_win) && count($arr_win) > 0) {
            $data = $dataProvider->getModels();
            if (is_array($data) && count($data) > 0) {
                foreach ($data as $key => $item) {
                    if (in_array($item->id, $arr_win)) {
                        $arr_win_result[] = ++$key;
//                        $arr_win_name[]=$item->filename;
                    }
                }
            }
        }

        return $this->render('scan', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'arr_win_result' => $arr_win_result,
        ]);
    }


}
